package com.yjz.study.listener

import android.graphics.Color
import androidx.recyclerview.widget.RecyclerView
import com.yjz.log.JLog
import com.yjz.log.util.DisplayUtil
import com.yjz.ui.util.ColorUtil
import kotlin.math.abs
import kotlin.math.min

/**
 * 商品详情页监听recyclerview滑动的距离来动态设置标题栏的背景色
 *
 * @param thresholdDp 滑动的距离
 * @param callback 到达滑动距离时，回调结果
 */
class GoodsDetailTitleScrollerListener(thresholdDp: Float = 100f, val callback: (Int) -> Unit) : RecyclerView.OnScrollListener() {

    private val thresholdPx = DisplayUtil.dp2px(thresholdDp)
    private var lastFraction = 0f

    override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
        super.onScrolled(recyclerView, dx, dy)
        val viewHolder = recyclerView.findViewHolderForAdapterPosition(0) ?: return
        val top = abs(viewHolder.itemView.top).toFloat()
        // 计算出当前滑动百分比
        val fraction = top / thresholdPx
        JLog.e("fraction = ", fraction)
        if (fraction > 1f) {
            lastFraction = fraction
            return
        }
        val newColor = ColorUtil.getCurrentColor(Color.TRANSPARENT, Color.WHITE, min(fraction, 1f))
        callback(newColor)
        lastFraction = fraction
    }
}